package com.linxs.topcham.application.fnas.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import org.apache.http.HttpResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.kissme.core.orm.Page;
import com.linxs.topcham.application.fnas.FansService;
import com.linxs.topcham.application.fnas.KdtapiService;
import com.linxs.topcham.application.org.AgencyOrgService;
import com.linxs.topcham.domain.fans.Fans;
import com.linxs.topcham.domain.fans.Order;
import com.linxs.topcham.domain.kdtapi.KdtFans;
import com.linxs.topcham.infrastruture.persist.kdtapi.KdtApiRepository;

@Service
public class KdtApiServiceImpl implements KdtapiService {

	private static final String KDT_APP = "kdtapp.properties";
	
	private Logger log = LoggerFactory.getLogger(KdtApiServiceImpl.class);

	@Autowired
	private FansService fansService;
	@Autowired
	private AgencyOrgService orgService;
	
	@Autowired
	private KdtApiRepository apiRepository;


	@Override
	public Page<KdtFans> query(Page<KdtFans> page) {
		page = apiRepository.query(page);
		List<KdtFans> result = Lists.newArrayList();
		for(KdtFans fans : page.getResult()) {
			Fans myFans = fansService.getFansByUserid(fans.getUserId());
			if (null != myFans) {
				fans.setOrg(orgService.get(myFans.getOrgId()));
			}
			
			result.add(fans);
		}
		page.setResult(result);
		return page;
	}

	@Override
	public List<Order> queryThisMonthAllStatusOrders() { 
		String method = "kdt.trades.sold.get";
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("fields", "tid,payment,buyer_nick,pay_time,status,title,weixin_user_id,receiver_name,receiver_mobile,receiver_state,receiver_city,receiver_district,receiver_address");

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, 0);
		c.set(Calendar.DAY_OF_MONTH, 1);
		String first = format.format(c.getTime());

		Calendar ca = Calendar.getInstance();
		ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
		String last = format.format(ca.getTime());

		params.put("start_created", first + " 00:00:00");
		params.put("end_created", last + " 23:59:59");

		params.put("page_size", "5000");
		KdtApiClient kdtApiClient;
		HttpResponse response;

		try {
			Properties props = new Properties();
			props = PropertiesLoaderUtils.loadAllProperties(KDT_APP);
			kdtApiClient = new KdtApiClient(props.getProperty("APP_ID"), props.getProperty("APP_SECRET"));

			response = kdtApiClient.get(method, params);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer result = new StringBuffer();
			String line = "";
			while ((line = bufferedReader.readLine()) != null) {
				result.append(line);
			}

			JSONObject json = new JSONObject(result.toString());
			JSONArray trades = new JSONArray(new JSONObject(json.getString("response")).getString("trades"));
			List<Order> orders = Lists.newArrayList();

			for (int i = 0; i < trades.length(); i++) {
				JSONObject item = trades.getJSONObject(i);

				Order order = new Order();
				order.setOrderId(item.getString("tid"));
				order.setPayment(new BigDecimal(item.getString("payment")).setScale(2, BigDecimal.ROUND_DOWN));
				order.setFansNick(item.getString("buyer_nick"));
				order.setPayTime(item.getString("pay_time"));
				order.setTitle(item.getString("title")); 
				order.setWeixinUserId(item.getString("weixin_user_id"));
				order.setReceiverName(item.getString("receiver_name"));
				order.setReceiverMobile(item.getString("receiver_mobile"));
				String address = item.getString("receiver_state") + item.getString("receiver_city") + item.getString("receiver_district") + item.getString("receiver_address");
				order.setAddress(address); 
				String status = item.getString("status");
				
				if("TRADE_NO_CREATE_PAY".equalsIgnoreCase(status)) {
					order.setStatus("没有创建支付交易");
				} else if("WAIT_BUYER_PAY".equalsIgnoreCase(status)) {
					order.setStatus("等待买家付款");
				} else if("WAIT_SELLER_SEND_GOODS".equalsIgnoreCase(status)) {
					order.setStatus("买家已付款，等待卖家发货");
				} else if("WAIT_BUYER_CONFIRM_GOODS".equalsIgnoreCase(status)) {
					order.setStatus("卖家已发货，等待买家确认收货");
				} else if("TRADE_BUYER_SIGNED".equalsIgnoreCase(status)) {
					order.setStatus("买家已签收");
				} else if("TRADE_CLOSED".equalsIgnoreCase(status)) {
					order.setStatus("付款以后用户退款成功，交易自动关闭");
				} else if("TRADE_CLOSED_BY_USER".equalsIgnoreCase(status)) {
					order.setStatus("付款以前，卖家或买家主动关闭交易");
				} else if("ALL_WAIT_PAY".equalsIgnoreCase(status)) {
					order.setStatus("没有创建支付交易,等待买家付款");
				} else if("ALL_CLOSED".equalsIgnoreCase(status)) {
					order.setStatus("付款前后，交易被买家或卖家主动关闭");
				}
				orders.add(order);
			}
			return orders;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	public List<Order> queryThisMonthOrders(String areas, String orderStatus) {
		String method = "kdt.trades.sold.get";
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("fields", "tid,payment,buyer_nick,pay_time,receiver_state,receiver_city,receiver_district,title,status,weixin_user_id");
		params.put("status", orderStatus);

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, 0);
		c.set(Calendar.DAY_OF_MONTH, 1);
		String first = format.format(c.getTime());

		Calendar ca = Calendar.getInstance();
		ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
		String last = format.format(ca.getTime());

		params.put("start_created", first + " 00:00:00");
		params.put("end_created", last + " 23:59:59");

		params.put("page_size", "5000");
		KdtApiClient kdtApiClient;
		HttpResponse response;

		try {
			Properties props = new Properties();
			props = PropertiesLoaderUtils.loadAllProperties(KDT_APP);
			kdtApiClient = new KdtApiClient(props.getProperty("APP_ID"), props.getProperty("APP_SECRET"));

			response = kdtApiClient.get(method, params);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer result = new StringBuffer();
			String line = "";
			while ((line = bufferedReader.readLine()) != null) {
				result.append(line);
			}

			JSONObject json = new JSONObject(result.toString());
			JSONArray trades = new JSONArray(new JSONObject(json.getString("response")).getString("trades"));
			List<Order> orders = Lists.newArrayList();

			for (int i = 0; i < trades.length(); i++) {
				JSONObject item = trades.getJSONObject(i);
				Order order = new Order();
				order.setOrderId(item.getString("tid"));
				order.setPayment(new BigDecimal(item.getString("payment")).setScale(2, BigDecimal.ROUND_DOWN));
				order.setFansNick(item.getString("buyer_nick"));
				order.setTitle(item.getString("title")); 
				order.setPayTime(item.getString("pay_time"));
				order.setStatus(item.getString("status"));
				order.setWeixinUserId(item.getString("weixin_user_id")); 
				
				String address = item.getString("receiver_state") + item.getString("receiver_city") + item.getString("receiver_district");
				if(address.indexOf(areas) != -1 || "全国地区".equals(areas)) { 
					order.setBase("0.05");
					order.setCommission(new BigDecimal("0.05").setScale(2, BigDecimal.ROUND_DOWN).multiply(order.getPayment()).setScale(2, BigDecimal.ROUND_DOWN));
				} else {
					order.setBase("0.03");
					order.setCommission(new BigDecimal("0.03").setScale(2, BigDecimal.ROUND_DOWN).multiply(order.getPayment()).setScale(2, BigDecimal.ROUND_DOWN));
				}
				
				orders.add(order);
			}
			return orders;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void deleteApiFansData() {
		apiRepository.delete();
	}

	@Override
	public List<Fans> query() { 
		String method = "kdt.users.weixin.followers.get";
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("page_size", "5000");
		KdtApiClient kdtApiClient;
		HttpResponse response;

		try {

			Properties props = new Properties();
			props = PropertiesLoaderUtils.loadAllProperties(KDT_APP);
			kdtApiClient = new KdtApiClient(props.getProperty("APP_ID"), props.getProperty("APP_SECRET"));

			response = kdtApiClient.get(method, params);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer result = new StringBuffer();
			String line = "";
			while ((line = bufferedReader.readLine()) != null) {
				result.append(line);
			}

			JSONObject json = new JSONObject(result.toString());
			JSONArray fanss = new JSONArray(new JSONObject(json.getString("response")).getString("users"));
			List<Fans> fansResult = Lists.newArrayList();

			for (int i = 0; i < fanss.length(); i++) {
				JSONObject item = fanss.getJSONObject(i);
				Fans fans = new Fans();
				
				JSONArray tags = new JSONArray(item.getString("tags"));
				String name = tags.isNull(0) ? "" : new JSONObject(tags.get(0).toString()).getString("name");
				fans.setAvatar(item.getString("avatar"))  
					.setTags(name.trim())
					.setCity(item.getString("city"))
					.setFollowTime(item.getString("follow_time"))
					.setNick(item.getString("nick"))
					.setProvince(item.getString("province"))
					.setSex(item.getString("sex"))
					.setUserId(item.getString("user_id"))
					.setWeixinOpenId(item.getString("weixin_openid"));

				fansResult.add(fans);
			}

			return fansResult;

		} catch (Exception e) {
			log.error("口袋通返回数据异常", e);
		}
		return Collections.emptyList();
	}

	@Override
	public void save(KdtFans kdtFans) {
		apiRepository.save(kdtFans); 
	}

	@Override
	public Page<Order> queryOrderPage(Page<Order> page) {
		String method = "kdt.trades.sold.get";
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("fields", "tid,payment,buyer_nick,pay_time,title,sign_time");
		params.put("status", "TRADE_BUYER_SIGNED");
		params.put("page_no", String.valueOf(page.getPageNo())); 
		params.put("page_size", String.valueOf(page.getPageSize()));
		KdtApiClient kdtApiClient;
		HttpResponse response;

		try {
			Properties props = new Properties();
			props = PropertiesLoaderUtils.loadAllProperties(KDT_APP);
			kdtApiClient = new KdtApiClient(props.getProperty("APP_ID"), props.getProperty("APP_SECRET"));

			response = kdtApiClient.get(method, params);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer result = new StringBuffer();
			String line = "";
			while ((line = bufferedReader.readLine()) != null) {
				result.append(line);
			}

			JSONObject json = new JSONObject(result.toString());
			JSONArray trades = new JSONArray(new JSONObject(json.getString("response")).getString("trades"));
			String total = new JSONObject(json.getString("response")).getString("total_results");
			page.setTotalCount(Long.valueOf(total));
			
			List<Order> orders = Lists.newArrayList();

			for (int i = 0; i < trades.length(); i++) {
				JSONObject item = trades.getJSONObject(i);

				Order order = new Order();
				order.setOrderId(item.getString("tid"));
				order.setPayment(new BigDecimal(item.getString("payment")));
				order.setFansNick(item.getString("buyer_nick"));
				order.setCommission(new BigDecimal("0.03").multiply(order.getPayment()));
				order.setPayTime(item.getString("sign_time"));
				order.setTitle(item.getString("title"));	 
				orders.add(order);
			}
			page.setResult(orders);
			return page;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public List<KdtFans> queryByTags(String tags) {
		return apiRepository.queryByTags(tags);
	}

	@Override
	public List<Order> queryThisMonthOrders(String orderStatus) {
		String method = "kdt.trades.sold.get";
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("fields", "tid,payment,buyer_nick,pay_time,sign_time,receiver_state,receiver_city,receiver_district,title,status,weixin_user_id");
		params.put("status", orderStatus);

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, 0);
		c.set(Calendar.DAY_OF_MONTH, 1);
		String first = format.format(c.getTime());

		Calendar ca = Calendar.getInstance();
		ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
		String last = format.format(ca.getTime());

		params.put("start_created", "2014-12-01 00:00:00");
		params.put("end_created", "2014-12-31 23:59:59");
//		params.put("start_created", first + " 00:00:00");
//		params.put("end_created", last + " 23:59:59");

		params.put("page_size", "5000");
		KdtApiClient kdtApiClient;
		HttpResponse response;

		try {
			Properties props = new Properties();
			props = PropertiesLoaderUtils.loadAllProperties(KDT_APP);
			kdtApiClient = new KdtApiClient(props.getProperty("APP_ID"), props.getProperty("APP_SECRET"));

			response = kdtApiClient.get(method, params);
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer result = new StringBuffer();
			String line = "";
			while ((line = bufferedReader.readLine()) != null) {
				result.append(line);
			}

			JSONObject json = new JSONObject(result.toString());
			JSONArray trades = new JSONArray(new JSONObject(json.getString("response")).getString("trades"));
			List<Order> orders = Lists.newArrayList();

			for (int i = 0; i < trades.length(); i++) {
				JSONObject item = trades.getJSONObject(i);
				Order order = new Order();
				order.setOrderId(item.getString("tid"));
				order.setPayment(new BigDecimal(item.getString("payment")).setScale(2, BigDecimal.ROUND_DOWN));
				order.setFansNick(item.getString("buyer_nick"));
				order.setTitle(item.getString("title")); 
				order.setPayTime(item.getString("sign_time"));	//签收日期
				order.setStatus(item.getString("status"));
				order.setWeixinUserId(item.getString("weixin_user_id")); 
				
				String address = item.getString("receiver_state") + item.getString("receiver_city") + item.getString("receiver_district");
				order.setAddress(address); 
				
				orders.add(order);
			}
			return orders;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public boolean isExist(String weixinOpenId) {
		KdtFans fans = apiRepository.get(weixinOpenId);
		
		return null != fans;
	}

}
